package com.yun.baymax.activity.account;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yun.baymax.R;
import com.yun.baymax.activity.BaseActivity;
import com.yun.baymax.bean.User;
import com.yun.baymax.utils.ChooseImageUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

import static cn.bmob.v3.BmobUser.getCurrentUser;


public class SettingActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_logout)
    AppCompatTextView tvLogout;
    @BindView(R.id.rl_sex)
    RelativeLayout rlSex;
    @BindView(R.id.rl_age)
    RelativeLayout rlAge;
    @BindView(R.id.tv_bind_phone)
    AppCompatTextView tvBindPhone;
    @BindView(R.id.tv_bind_email)
    AppCompatTextView tvBindEmail;
    @BindView(R.id.tv_reset_pwd)
    AppCompatTextView tvResetPwd;
    @BindView(R.id.tv_change_pwd)
    AppCompatTextView tvChangePwd;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    private ChooseImageUtil mChooseImageUtil;
    private User currentUser;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initVariables() {
        ButterKnife.bind(this);
        toolbar.setNavigationIcon(R.drawable.arrow_back);
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setTitle(getCurrentUser().getUsername());
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        currentUser = BmobUser.getCurrentUser(User.class);
        initViewData();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        fetchData();
        srl.setColorSchemeResources(R.color.colorPrimary, R.color.text_color_blue, R.color.voucher_color_red);
        srl.setNestedScrollingEnabled(true);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchData();
            }
        });
    }

    private void fetchData() {
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.addWhereEqualTo("username", getCurrentUser().getUsername());
        bmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                srl.setRefreshing(false);
                if (e == null) {
                    if (list != null) {
                        currentUser = list.get(0);
                        currentUser.update();
                        initViewData();
                    }
                } else {
                    showToast(e.getMessage());
                }
            }
        });
    }

    @Override
    protected void loadData() {

    }

    private void initViewData() {

        String keyNickName = currentUser.getNick();

        String keyComment = currentUser.getContent();
        int keyAge = currentUser.getAge();

        boolean keySex = currentUser.getSex();

        tvNickname.setText(TextUtils.isEmpty(keyNickName) ? "点击设置昵称" : keyNickName);

        tvComment.setText(TextUtils.isEmpty(keyComment) ? "点击设置签名" : keyComment);

        tvAge.setText(keyAge == 0 ? "" : keyAge + "");

        tvSex.setText(keySex ? "男" : "女");

        String headImageUrl = currentUser.getHeadImage();
        if (!TextUtils.isEmpty(headImageUrl)) {
//            Glide.with()
        }

        String mobilePhone = currentUser.getMobilePhoneNumber();
        Boolean phoneVerified = currentUser.getMobilePhoneNumberVerified();

        if (mobilePhone != null) {
            tvBindPhone.setText("手机号:" + mobilePhone + (phoneVerified ? "已绑定" : "待绑定"));
        } else {
            tvBindPhone.setText("绑定手机号");
        }

        String email = currentUser.getEmail();

        if (TextUtils.isEmpty(email)) {
            tvBindEmail.setText("绑定邮箱");
        } else {
            tvBindEmail.setText("邮箱:" + email);
        }

    }

    private void updateUserInfo(User currentUser) {
        currentUser.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    showToast("更新成功");
                    initViewData();
                } else {
                    showToast("更新失败");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 0:// 相册

                if (resultCode == RESULT_OK && data != null && mChooseImageUtil != null) {
                    String imageFromPicker = mChooseImageUtil.getImageFromPicker(this, data);
                    if (!TextUtils.isEmpty(imageFromPicker)) {
                        uploadImage(imageFromPicker);
                    }
                }

                break;

            case 1:// 相机
                if (resultCode == RESULT_OK) {
                    File fs = new File(getExternalCacheDir(), "cache.jpg");
                    if (fs != null && fs.exists()) {
                        uploadImage(fs.getPath());
                    }
                }

                break;

            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 10: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mChooseImageUtil.getImageFromCamer();
                } else {
                    Snackbar.make(rlAge, "相机权限,未开启!", 3000).show();
                }
                return;
            }

            case 11: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mChooseImageUtil.getImageFromPick();
                } else {
                    Snackbar.make(rlAge, "SD卡权限,未开启!", 3000).show();
                }
                return;
            }
        }
    }

    private void uploadImage(String path) {
        final BmobFile bmobFile = new BmobFile(new File(path));
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
                    currentUser.setHeadImage(bmobFile.getFileUrl());
                    showToast("上传文件成功:");
                    updateUserInfo(currentUser);
                } else {
                    showToast("上传文件失败：" + e.getMessage());
                }
            }
        });
    }

    @OnClick({R.id.iv_head, R.id.tv_nickname, R.id.tv_comment, R.id.rl_sex, R.id.rl_age, R.id.tv_logout, R.id.tv_bind_phone, R.id.tv_bind_email, R.id.tv_reset_pwd, R.id.tv_change_pwd})
    public void onClick(View view) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        switch (view.getId()) {
            case R.id.iv_head:

                if (mChooseImageUtil == null) {
                    mChooseImageUtil = new ChooseImageUtil(this);
                }
                mChooseImageUtil.showChooseDialog(null);

                break;
            case R.id.tv_nickname:
                showDialog("设置昵称", tvNickname.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        currentUser.setNick(value);
                        updateUserInfo(currentUser);
                    }
                });

                break;
            case R.id.tv_comment:
                showDialog("设置签名", tvComment.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        currentUser.setContent(value);
                        updateUserInfo(currentUser);
                    }
                });
                break;
            case R.id.rl_sex:
                dialog.setTitle("请选择性别")
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("男", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                currentUser.setSex(true);
                                updateUserInfo(currentUser);
                            }
                        })
                        .setNegativeButton("女", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                currentUser.setSex(false);
                                updateUserInfo(currentUser);
                            }
                        }).show();
                break;
            case R.id.rl_age:

                showDialog("设置年龄", tvAge.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        if (TextUtils.isEmpty(value)) {
                            currentUser.setAge(0);
                            updateUserInfo(currentUser);
                        } else {
                            try {
                                int i = Integer.parseInt(value);
                                currentUser.setAge(i);
                                updateUserInfo(currentUser);
                            } catch (Exception e) {
                                showToast("年龄请输入数字");
                            }
                        }
                    }
                });
                break;
            case R.id.tv_logout:
                dialog.setMessage("确认退出?").setTitle("注销").setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        BmobUser.logOut();
                        goNext(null, LoginActivity.class);
                        finish();
                    }
                }).show();
                break;
            case R.id.tv_bind_phone:

                goNext(null, BindPhoneActivity.class);

                break;
            case R.id.tv_bind_email:

                goNext(null, BindEmailActivity.class);

                break;

            case R.id.tv_change_pwd:

                if (currentUser != null) {
                    goNext(null, ChangePasswordActivity.class);
                } else {
                    showToast("请登录!");
                }

                break;
            case R.id.tv_reset_pwd:

                String email = currentUser.getEmail();

                //bug 返回值为null
//                Boolean emailVerified = currentUser.getEmailVerified();

//                if (email != null && emailVerified) {
                if (email != null) {
                    goNext(null, ForgetPasswordActivity.class);
                } else {
                    showToast("请先绑定邮箱!");
                }

                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initViewData();
    }

    private void showDialog(String title, final String value, final OnValueChangeListener listener) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        final EditText et = new EditText(this);
        et.setText(TextUtils.isEmpty(value) ? "" : value);
        et.setSelection(TextUtils.isEmpty(value) ? 0 : value.length());
        dialog.setTitle(title);
        dialog.setView(et);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = et.getText().toString();
                if (!TextUtils.equals(s, value) && listener != null) {
                    listener.onChangedValue(s);
                }
                dialogInterface.dismiss();
            }
        });

        dialog.show();

    }

    interface OnValueChangeListener {
        void onChangedValue(String value);
    }

}
